﻿namespace Util
{
    using System.Drawing;
    using System.Drawing.Imaging;

    public static class ImageProcessor
    {
        public static ulong GetPerceptionHashCode(Image img)
        {
            const int kWidth = 8;
            const int kSquare = kWidth * kWidth;

            // Resize
            Bitmap bmp = new Bitmap(img, kWidth, kWidth);
            int[] gray = new int[kSquare];

            int avg = 0;
            for (int i = 0; i < bmp.Height; ++i)
            {
                for (int j = 0; j < bmp.Width; ++j)
                {
                    Color c = bmp.GetPixel(j, i);
                    // Convert to gray level
                    int ret = (int)(c.R * 0.299 + c.G * 0.587 + c.B * 0.114);
                    gray[i * kWidth + j] = ret;
                    avg += ret;
                }
            }
            avg /= kSquare;

            ulong finger = 0;
            for (int i = 0; i < kSquare; ++i)
            {
                finger |= ((gray[i] < avg ? 0 : (((ulong)1) << (kSquare - i - 1))));
            }
            return finger;
        }

        public static int[] GetColorHistogramVector(Image img)
        {
            const int kWidth = 32;
            const int kSize = 64;
            int[] pixCnt = new int[kSize];

            Bitmap bmp = new Bitmap(img, new Size(kWidth, kWidth));
            for (int i = 0; i < bmp.Width; ++i)
            {
                for (int j = 0; j < bmp.Height; ++j)
                {
                    Color c = bmp.GetPixel(i, j);
                    int idx = (c.R / 64) * 16 + (c.G / 64) * 4 + c.B / 64;
                    ++pixCnt[idx];
                }
            }
            return pixCnt;
        }

        /// <summary>
        /// 得到指定mimeType的ImageCodecInfo
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns></returns>
        public static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }
    }
}
